package com.rc.activity;

import android.app.Activity;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.rc.activity.dao.tbl_Category;
import com.rc.activity.dao.tbl_Item;
import com.rc.activity.dao.tbl_Receipt;
import com.rc.activity.dao.tbl_ReceiptDao;
import com.rc.activity.dao.tbl_Trip;
import com.rc.activity.provider.Contract;
import com.rc.db.DatabaseSupport;
import com.rc.util.SharedObjects;
import com.rc.util.Util;
import com.telpoo.frame.ui.BaseActivity;

public class ReceiptBoxDetailAddItem extends BaseActivity implements
		OnClickListener {

	public static void callItent(Activity ct, long mReceiptID,
			boolean isMerchant) {
		Intent it = new Intent(ct, ReceiptBoxDetailAddItem.class);
		it.putExtra("RECEIPT_ID", mReceiptID);
		it.putExtra("IS_MERCHANT", isMerchant);
		ct.startActivity(it);
		ct.finish();
	}

	public static void callItentCombile(Activity ct, float mReceiptID,
			float mAmount) {
		Intent it = new Intent(ct, ReceiptBoxDetailAddItem.class);
		it.putExtra("RECEIPT_ID", mReceiptID);
		it.putExtra("AMOUNT", mAmount);
		ct.startActivity(it);
		ct.finish();
	}

	private float amount = 0;
	private long mReceiptID = 0;
	private LinearLayout llSave, llCancel;
	private TextView txtCategory, txtTripName, txtAmount, txtItemName, txtMemo,
			lbCategory;

	private tbl_Category objCategory;
	private tbl_Trip objTrip;
	private tbl_Item objItem;
	private MyReceiver myReceiver;
	public static final String ACTION = "com.rc.receipt";

	@Override
	public void onStart() {
		// Register BroadcastReceiver
		// to receive event from our service
		myReceiver = new MyReceiver();
		IntentFilter intentFilter = new IntentFilter();
		intentFilter.addAction(ACTION);
		SharedObjects.context.registerReceiver(myReceiver, intentFilter);

		super.onStart();
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
	}

	@Override
	public void onStop() {
		// TODO Auto-generated method stub
		SharedObjects.context.unregisterReceiver(myReceiver);
		super.onStop();
	}

	@Override
	protected void onCreate(Bundle arg0) {
		// TODO Auto-generated method stub
		super.onCreate(arg0);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.receiptdetail_edititem);
		((TextView) findViewById(R.id.txtTitle))
				.setText(getString(R.string.add_item));

		llCancel = (LinearLayout) findViewById(R.id.llCancel);
		llSave = (LinearLayout) findViewById(R.id.llSave);
		txtCategory = (TextView) findViewById(R.id.txtCategory);
		txtTripName = (TextView) findViewById(R.id.txtTripName);
		txtItemName = (TextView) findViewById(R.id.txtItemName);
		txtAmount = (TextView) findViewById(R.id.txtAmount);
		lbCategory = (TextView) findViewById(R.id.lbCategory);
		txtMemo = (TextView) findViewById(R.id.txtMemo);

		txtTripName.setOnClickListener(this);
		txtCategory.setOnClickListener(this);
		llCancel.setOnClickListener(this);
		llSave.setOnClickListener(this);
		txtCategory.setEnabled(false);

		objItem = new tbl_Item();
		if (getIntent() != null) {
			mReceiptID = getIntent().getLongExtra("RECEIPT_ID", 0);
		}
		if (getIntent().hasExtra("AMOUNT")) {
			amount = getIntent().getFloatExtra("AMOUNT", 0);
			txtAmount.setText(Util.convertFloat(amount + "") + "");
			txtItemName.setText(getString(R.string.combined));
		}
		txtAmount.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				if (!Util.validateFloat2Decimal(txtAmount.getText().toString())) {
					txtAmount
							.setText(txtAmount
									.getText()
									.toString()
									.substring(
											0,
											txtAmount.getText().toString()
													.length() - 1));
				}
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub

			}

			@Override
			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub

			}
		});
	}

	/**
	 * insert Item
	 */
	private int insertData() {

		objItem.setItemID(Long.valueOf(Util.getCurrentTime()));
		objItem.setReceiptID(mReceiptID);
		long mCategoryID = getString(R.string.choose_category).equals(
				txtCategory.getText().toString()) ? 0 : objCategory
				.getCategoryID();
		objItem.setCategoryID(mCategoryID);
		long mTripID = getString(R.string.choose_trip).equals(
				txtTripName.getText().toString()) ? 0 : objTrip.getTripID();
		objItem.setTripID(mTripID);
		objItem.setName(txtItemName.getText().toString());
		objItem.setAmount(Util.formatStringFloat(Util.convertFloat(txtAmount
				.getText().toString())));
		objItem.setMemo(txtMemo.getText().toString());
		objItem.setIsCreate("1");
		objItem.setIsDelete("");
		return DatabaseSupport.createNewItem(objItem,
				ReceiptBoxDetailAddItem.this);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == 1) {
			if (data.getExtras().containsKey("CATEGORY_ID")) {
				long mCategoryID = data.getLongExtra("CATEGORY_ID", 0);
				objCategory = new tbl_Category();
				objCategory = DatabaseSupport
						.getCategoryByID(mCategoryID, this);
				txtCategory.setText(objCategory.getName());
			}
		} else if (resultCode == 2) {
			if (data.getExtras().containsKey("TRIP_ID")) {
				long mTripID = data.getLongExtra("TRIP_ID", 0);
				objTrip = new tbl_Trip();
				objTrip = DatabaseSupport.getTripByID(mTripID, this);
				txtTripName.setText(objTrip.getName());
				txtCategory.setVisibility(View.VISIBLE);
				lbCategory.setVisibility(View.VISIBLE);
			}
		}

	}

	/**
	 * validate UI
	 */

	private boolean validateUI() {
		if (!Util.validateText(txtItemName)) {
			Util.setError((EditText) txtItemName,
					getString(R.string.input_item_name));
		} else if (!Util.validateText(txtAmount)) {
			Util.setError((EditText) txtAmount,
					getString(R.string.input_item_amount));
		} else if (getString(R.string.choose_category).equals(
				txtCategory.getText().toString())
				&& !getString(R.string.choose_trip).equals(
						txtTripName.getText().toString())) {
			showToast(getString(R.string.choose_category));
			CategorizeItems.callIntent(ReceiptBoxDetailAddItem.this);
		} else {
			return true;
		}
		return false;
	}

	/**
	 * Dialog edit total
	 */
	private float subtotal = 0;
	private float tax = 0;
	private float discount = 0;
	private float total = 0;

	private void createDialogEditTotal() {
		subtotal = 0;
		tax = 0;
		discount = 0;
		total = 0;
		Dialog dialog = new Dialog(this);
		dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		dialog.setCancelable(false);
		dialog.setCanceledOnTouchOutside(false);
		dialog.setContentView(R.layout.dialog_receiptdetail_total);
		((LinearLayout) dialog.findViewById(R.id.llCancel))
				.setVisibility(View.GONE);

		final TextView txtTotal = (TextView) dialog.findViewById(R.id.txtTotal);

		final TextView txtSubTotal = (TextView) dialog
				.findViewById(R.id.txtSubTotal);

		final TextView txtTax = (TextView) dialog.findViewById(R.id.txtTax);

		final TextView txtDiscount = (TextView) dialog
				.findViewById(R.id.txtDiscount);
		subtotal = Util.convertFloat(objItem.getAmount());
		total = subtotal + tax - discount;
		txtTax.setText(tax + "");
		txtSubTotal.setText(subtotal + "");
		txtDiscount.setText(discount + "");
		txtTotal.setText(total + "");
		dialog.show();

		((LinearLayout) dialog.findViewById(R.id.llSave))
				.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						tbl_Receipt objReceipt = new tbl_Receipt();
						objReceipt = DatabaseSupport.getReceiptByID(mReceiptID,
								ReceiptBoxDetailAddItem.this);
						if (objReceipt == null) {
							return;
						}
						objReceipt
								.setDiscount(txtDiscount.getText().toString());
						objReceipt.setTax(txtTax.getText().toString());
						objReceipt
								.setSubtotal(txtSubTotal.getText().toString());
						objReceipt.setTotal(txtTotal.getText().toString());
						objReceipt.setIsUpdate("1");
						if (ReceiptBoxDetailAddItem.this
								.getContentResolver()
								.update(Contract.CONTENT_URI_RECEIPT,
										objReceipt.getContentValues(),
										tbl_ReceiptDao.Properties.ReceiptID.columnName
												+ " = " + mReceiptID, null) != -1) {
							ReceiptBox.callIntent(ReceiptBoxDetailAddItem.this,
									4 + "", 1);
						}

					}
				});
		txtTax.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				float subtotal = Float
						.valueOf(txtSubTotal.getText().toString());
				float tax = 0;
				if (!"".equals(txtTax.getText().toString())) {
					tax = Util.convertFloat(txtTax.getText().toString());
				}
				float discount = 0;
				if (!"".equals(txtDiscount.getText().toString())) {
					discount = Util.convertFloat(txtDiscount.getText()
							.toString());
				}
				float total = subtotal + tax - discount;
				txtTotal.setText(total + "");
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub

			}

			@Override
			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub

			}
		});
		txtDiscount.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				float subtotal = Float
						.valueOf(txtSubTotal.getText().toString());
				float tax = 0;
				if (!"".equals(txtTax.getText().toString())) {
					tax = Util.convertFloat(txtTax.getText().toString());
				}
				float discount = 0;
				if (!"".equals(txtDiscount.getText().toString())) {
					discount = Util.convertFloat(txtDiscount.getText()
							.toString());
				}
				float total = subtotal + tax - discount;
				txtTotal.setText(total + "");
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub

			}

			@Override
			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub

			}
		});

	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.llSave:
			if (validateUI()) {
				if (insertData() > 0) {
					if (amount > 0) {
					} else {
						if (getIntent().hasExtra("IS_MERCHANT")) {
							boolean isMerchant = getIntent().getBooleanExtra(
									"IS_MERCHANT", false);
							if (isMerchant) {
								createDialogEditTotal();
							} else {
								ReceiptBox.callIntent(ReceiptBoxDetailAddItem.this, mReceiptID+"", 4);
							}
						}
					}
				}

			}
			break;
		case R.id.llCancel:
			ReceiptBox.callIntent(ReceiptBoxDetailAddItem.this,
					mReceiptID + "", 4);
			// finish();
			break;
		case R.id.txtCategory:
			CategorizeItems.callIntent(this);
			break;
		case R.id.txtTripName:
			TripList.callIntent(this);
			break;
		default:
			break;
		}
	}

	@Override
	public void onBackPressed() {
		super.onBackPressed();
		ReceiptBox.callIntent(ReceiptBoxDetailAddItem.this, mReceiptID + "", 4);
		// finish();
	}

	/**
	 * 
	 */
	private class MyReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context arg0, Intent arg1) {
			Log.e("TRIP_SYNC", "SYC");
		}

	}

}
